﻿using System;
using System.Collections.Generic;
using System.Data.Objects;
using System.Linq;
using CML.Intercamber.Business.Model;

namespace CML.Intercamber.Business.Dao
{
    public class StatsDao
    {
        public static List<StatConnectionDetail> StatsConnection(DateTime from, DateTime to, string detail)
        {
            List<StatConnectionDetail> res;
            using (var context = new IntercamberEntities())
            {
                var req = context.UserConnections.Where(x => x.DateConnection >= from && x.DateConnection <= to);
                if (detail == "hour")
                {
                    // detail by hour 
                    var t = (from i in req
                           group i by
                               new
                               {
                                   y = i.DateConnection.Year,
                                   m = i.DateConnection.Month,
                                   d = i.DateConnection.Day,
                                   h = i.DateConnection.Hour
                               }
                               into g
                               select new 
                               {
                                   g.Key.y, g.Key.m, g.Key.d, g.Key.h, 
                                   Number = g.Count()
                               }).ToList();
                    res = (from i in t
                        select new StatConnectionDetail
                        {
                            Date = new DateTime(i.y, i.m, i.d, i.h, 0, 0),
                            Number = i.Number
                        }).ToList();
                }
                else
                {
                    // detail by day
                    res = ( from i in req
                            group i by EntityFunctions.TruncateTime(i.DateConnection)
                            into g
                            select new StatConnectionDetail
                            {
                                Date = g.Key.Value,
                                Number = g.Count()
                            }).ToList();
                }
            }
            return res;
        }

    }
}
